package vietnam.traveltools;

import java.sql.SQLException;
import java.util.ArrayList;

import vietnam.traveltools.adapter.HotelAdapter;
import vietnam.traveltools.module.LoadMoreListView;
import vietnam.traveltools.module.LoadMoreListView.OnLoadMoreListener;
import vietnam.traveltools.variables.ListItem;
import vietnam.traveltools.variables.MySQLiteOpenHelper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class HotelActivity extends Activity implements OnClickListener {
	private static final String TAG = "HotelActivity";
	private EditText etSearch;
	private Button btnSearch;
	private Button btnVoiceSearch;
	private Button btnClear;
	protected static final int RESULT_SPEECH = 1;
	private ListView list;
	private HotelAdapter hotelAdapter;
	private int i = 0;
	private MySQLiteOpenHelper dataHelper;
	private ArrayList<ListItem> arlHotel = new ArrayList<ListItem>();
	private Runnable updateTask;
	private Handler guiThread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setTitle("Hotel");
		try {
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
			getActionBar().setDisplayHomeAsUpEnabled(true);
			setContentView(R.layout.hotel_activity);
			setupUI(findViewById(R.id.parent));

			etSearch = (EditText) findViewById(R.id.etSearch);
			btnSearch = (Button) findViewById(R.id.btnSearch);
			btnClear = (Button) findViewById(R.id.btnClear);
			btnVoiceSearch = (Button) findViewById(R.id.btnVoiceSearch);
			
			etSearch.setText(""); 

			btnClear.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					((EditText) etSearch).setText("");

				}
			});

			btnVoiceSearch.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

					Intent intent = new Intent(
							RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

					intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
							"en-US");

					try {
						startActivityForResult(intent, RESULT_SPEECH);

						etSearch.setText("");
					} catch (ActivityNotFoundException a) {
						Toast t = Toast
								.makeText(
										getApplicationContext(),
										"Ối, có vẻ thiết bị của bạn không hỗ trợ chức năng này",
										Toast.LENGTH_SHORT);
						t.show();
					}

				}
			});

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error starting activity: " + e, Toast.LENGTH_LONG).show();
		}

		/*---------------Database begin------------- */

		try {
			try {

				dataHelper = new MySQLiteOpenHelper(HotelActivity.this);
				dataHelper.checkAndcopyDB();
				dataHelper.openDB();
			} catch (SQLException sqle) {
				Log.d(TAG, "database error: " + sqle);
				Toast.makeText(getApplicationContext(), "Error: " + sqle,
						Toast.LENGTH_LONG).show();
			}
			if (etSearch.getText().toString().trim().compareTo("") == 0) {
				String sql = "SELECT * FROM "
						+ MySQLiteOpenHelper.tb_name_hotel + " WHERE "
						+ MySQLiteOpenHelper.cl_id_hotel + " > " + i + " AND "
						+ MySQLiteOpenHelper.cl_id_hotel + " < " + (i + 15);

				Log.d(TAG, sql);

				getAndPrintData(sql, i);

				list = (ListView) findViewById(R.id.list);

				hotelAdapter = new HotelAdapter(this, list.getId(), arlHotel);

				list.setAdapter(hotelAdapter);
			}

			/*---------------Database end------------- */

			innitThread();
			etSearch.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence cs, int arg1, int arg2,
						int arg3) {
					queueUpdate(500);

				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
					list.setAdapter(null);
				}

				@Override
				public void afterTextChanged(Editable arg0) {

				}
			});
			// //
			EditText etSearch = (EditText) findViewById(R.id.etSearch);
			if (etSearch.getText().toString().trim().compareTo("") != 0) {
				((LoadMoreListView) list)
						.setOnLoadMoreListener(new OnLoadMoreListener() {
							public void onLoadMore() {

								int i = 14;
								String sql = "SELECT * FROM "
										+ MySQLiteOpenHelper.tb_name_hotel
										+ " WHERE "
										+ MySQLiteOpenHelper.cl_id_hotel
										+ " > " + i + " AND "
										+ MySQLiteOpenHelper.cl_id_hotel
										+ " < " + (i + 15);

								getAndPrintData(sql, i);

								((LoadMoreListView) list).onLoadMoreComplete();
							}

						});
			}

		} catch (Exception e) {
			Log.d(TAG, "Query error!");
			Toast.makeText(getApplicationContext(), "Error: " + e,
					Toast.LENGTH_LONG).show();
		}

	}

	private void innitThread() {
		guiThread = new Handler();
		updateTask = new Runnable() {

			@Override
			public void run() {
				EditText etSearch = (EditText) findViewById(R.id.etSearch);
				String word = etSearch.getText().toString().trim();

				if (word.equalsIgnoreCase("")) {
					int i = 0;
					String sql = "SELECT * FROM "
							+ MySQLiteOpenHelper.tb_name_hotel + " WHERE "
							+ MySQLiteOpenHelper.cl_id_hotel + " > " + i
							+ " AND " + MySQLiteOpenHelper.cl_id_hotel + " < "
							+ (i + 15);

					Log.d(TAG, sql);

					getAndPrintData(sql, i);

					list = (ListView) findViewById(R.id.list);

					hotelAdapter = new HotelAdapter(HotelActivity.this,
							list.getId(), arlHotel);

					list.setAdapter(hotelAdapter);
				} else {
					hotelAdapter.clear();

					String sql = "SELECT * FROM "
							+ MySQLiteOpenHelper.tb_name_hotel + " WHERE "
							+ MySQLiteOpenHelper.cl_hotel_name + " LIKE '%"
							+ etSearch.getText().toString().trim() + "%' OR "
							+ MySQLiteOpenHelper.cl_hotel_address + " LIKE '%"
							+ etSearch.getText().toString().trim() + "%' OR "
							+ MySQLiteOpenHelper.cl_hotel_city + " LIKE '%"
							+ etSearch.getText().toString().trim() + "%'";

					list.setAdapter(null);
					int i = 0;

					getAndPrintData(sql, i);

					hotelAdapter.notifyDataSetChanged();

					list = (ListView) findViewById(R.id.list);

					hotelAdapter = new HotelAdapter(HotelActivity.this,
							list.getId(), arlHotel);

					list.setAdapter(hotelAdapter);

				}

			}
		};
	}

	private void queueUpdate(long delayMillisecond) {
		guiThread.removeCallbacks(updateTask);
		guiThread.postDelayed(updateTask, delayMillisecond);

	}

	public void getAndPrintData(String sql, int i) {
		Cursor cursor = dataHelper.SELECTSQL(sql);
		if (cursor != null) {
			if (cursor.moveToFirst()) {

				do {
					int get_cl_id_hotel = cursor.getInt(cursor
							.getColumnIndex(MySQLiteOpenHelper.cl_id_hotel));

					String get_cl_name = cursor.getString(cursor
							.getColumnIndex(MySQLiteOpenHelper.cl_hotel_name));

					String get_cl_address = cursor
							.getString(cursor
									.getColumnIndex(MySQLiteOpenHelper.cl_hotel_address));

					String get_cl_city = cursor.getString(cursor
							.getColumnIndex(MySQLiteOpenHelper.cl_hotel_city));

					String get_cl_price = cursor.getString(cursor
							.getColumnIndex(MySQLiteOpenHelper.cl_hotel_price));

					if (get_cl_price == null) {
						get_cl_price = "Đang cập nhật";
					}
					String get_cl_phone = cursor.getString(cursor
							.getColumnIndex(MySQLiteOpenHelper.cl_hotel_phone));
					if (get_cl_phone == null) {
						get_cl_phone = "Đang cập nhật";
					}

					String get_cl_fax = cursor.getString(cursor
							.getColumnIndex(MySQLiteOpenHelper.cl_hotel_fax));
					if (get_cl_fax == null) {
						get_cl_fax = "Đang cập nhật";
					}

					String get_cl_star = cursor.getString(cursor
							.getColumnIndex(MySQLiteOpenHelper.cl_hotel_star));

					Log.d(TAG, "id_hotel: " + get_cl_id_hotel);
					arlHotel.add(i++, new ListItem(get_cl_id_hotel,
							get_cl_name, "Địa chỉ: " + get_cl_address,
							"Tỉnh/Thành phố: " + get_cl_city, "*" + get_cl_star
									+ "*", "Điện thoại\n" + get_cl_phone,
							"---Fax---\n" + get_cl_fax, "---Giá---\n"
									+ get_cl_price,0));

				} while (cursor.moveToNext());
			}
		}
	}

	public static void hideSoftKeyboard(Activity activity) {
		InputMethodManager inputMethodManager = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
				.getWindowToken(), 0);
	}

	public void setupUI(View view) {

		// Set up touch listener for non-text box views to hide keyboard.
		if (!(view instanceof EditText)) {

			view.setOnTouchListener(new View.OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {
					hideSoftKeyboard(HotelActivity.this);
					return false;
				}

			});
		}

		// If a layout container, iterate over children and seed recursion.
		if (view instanceof ViewGroup) {

			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

				View innerView = ((ViewGroup) view).getChildAt(i);

				setupUI(innerView);
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.overridePendingTransition(R.anim.bottom_in, R.anim.top_out);
			onBackPressed();

			break;

		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case RESULT_SPEECH: {
			if (resultCode == RESULT_OK && null != data) {

				ArrayList<String> text = data
						.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

				etSearch.setText(text.get(0));
			}
			break;
		}

		}
	}

}
